package com.qianfeng.smartplatform.service.impl;/*
 *@Description:
 *@author:赵健
 *@Date:zjzzz 2022/9/9 8:40
 */

import com.qianfeng.smartplatform.cache.SceneCache;
import com.qianfeng.smartplatform.constans.ResultCode;
import com.qianfeng.smartplatform.exceptions.FindDataException;
import com.qianfeng.smartplatform.mapper.SceneMapper;
import com.qianfeng.smartplatform.pojo.Scene;
import com.qianfeng.smartplatform.pojo.SysUserInfo;
import com.qianfeng.smartplatform.service.SceneService;
import com.qianfeng.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
public class SceneServiceImpl implements SceneService {
    @Autowired
    private SceneMapper sceneMapper;

    @Autowired
    private SceneCache sceneCache;


    @Override
    public void addScene(Scene scene) {
        //将数据插入到数据库
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        scene.setCreateBy(loginUser.getUId());
        //添加数据
        sceneMapper.insertSelective(scene);
    }

    @Override
    public void updateScene(Scene scene) {
        sceneMapper.updateByPrimaryKeySelective(scene);
    }

    @Override
    public Scene getSceneById(Long id) {
        //根据用户id查询用户所有的场景
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        List<Scene> sceneList=sceneCache.get(loginUser.getUId());
        Assert.notNull(sceneList,()->{
            throw new FindDataException("当前场景不存在", ResultCode.DATA_NOT_EXIST);
        });

        //获取当前id对应的场景数量
        List<Scene> list = sceneList.stream().filter(scene -> scene.getSceneId().equals(id)).collect(Collectors.toList());
        //如果有这个场景，长度就一定1
        Assert.isTrue(list.size()==1,()->{
            throw new FindDataException("当前场景不存在", ResultCode.DATA_NOT_EXIST);
        });
        return list.get(0);
    }

    @Override
    public List<Scene> getAllScenesByUser() {
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        List<Scene> sceneList = sceneCache.get(loginUser.getUId());
        return sceneList;
    }

    @Override
    public void deleteScenes(List<Long> ids) {

    }
}
